var started = false;

// recieves messages from background page
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if ((request.greeting == "launchUI") && !started) {
      started = true;
      showUI();
      sendResponse();
    }
  }
);

function showUI(){
  prepareCanvas();
  document.documentElement.style.overflow = 'hidden';
  document.documentElement.style.height = '100%';
}

var containerDiv;
var confirmButton;
var cancelButton;
var canvasContainer;
var myCanvas;
var canvas;
var ctx;
var canvasOffset;
var offsetX;
var offsetY;
var isDrawing = false;
var hasDrawing = false;
var hasDrawn = false;
var startX;
var startY;
var endX;
var endY;
var doc;
var scrollLeft;
var scrollTop;

function prepareCanvas() {
  var body = document.body,
  html = document.documentElement;

  var height = Math.max( body.scrollHeight, body.offsetHeight, 
    html.clientHeight, html.scrollHeight, html.offsetHeight );

  var width = Math.max( body.scrollWidth, body.offsetWidth, 
    html.clientWidth, html.scrollWidth, html.offsetWidth );



  // Create a blank div where we are going to put the canvas into.
  canvasContainer = document.createElement('div');
  // Add the div into the document
  $(canvasContainer).appendTo(document.documentElement);
  canvasContainer.style.position="absolute";
  // Set to 100% so that it will have the dimensions of the document
  canvasContainer.style.left="0px";
  canvasContainer.style.top="0px";
  canvasContainer.style.width=width+"px";
  canvasContainer.style.height=height+"px";
  // Set to high index so that this is always above everything else
  // (might need to be increased if you have other element at higher index)
  canvasContainer.style.zIndex="1000";
  
  var superContainer = document.body;
  
  // Now we create the canvas
  myCanvas = document.createElement('canvas');
  myCanvas.style.width = canvasContainer.scrollWidth+"px";
  myCanvas.style.height = canvasContainer.scrollHeight+"px";
  // You must set this otherwise the canvas will be streethed to fit the container
  myCanvas.width=superContainer.scrollWidth;
  myCanvas.height=superContainer.scrollHeight;
  myCanvas.style.overflow = 'visible';
  myCanvas.style.position = 'absolute';
  myCanvas.id = 'canvas';

  // Add int into the container
  canvasContainer.appendChild(myCanvas);
  canvas = myCanvas;
  ctx = canvas.getContext("2d");
  canvasOffset = $("#canvas").offset();
  offsetX = canvasOffset.left;
  offsetY = canvasOffset.top;

  // Initiate GUI controls
  startGUI();

  // moving cursor change here so user can start crop with the right tool
  canvas.style.cursor = "crosshair";
  
  $("#canvas").on('mousedown', function (e) {
    handleMouseDown(e);
  }).on('mouseup', function(e) {
    handleMouseUp(e);
  }).on('mousemove', function(e) {
    handleMouseMove(e);
  });
}

function startGUI() {
  //create iframe, inject with buttons.
  chrome.runtime.sendMessage({greeting: "getButtons"}, function(html) {
    var controlBar = document.createElement('iframe');
    controlBar.id = 'control_bar';
    controlBar.srcdoc = html;
    document.documentElement.appendChild(controlBar);
  });

  paintBlack();
}

function paintBlack(){
  ctx.globalAlpha = 0.6;

  ctx.beginPath();
  ctx.rect(0, 0, canvas.width, canvas.height);
  ctx.fill();
}

window.onmessage = function(message) {
  if (message.data == 'confirm' && hasDrawn) {
    canvasContainer.remove();
    $('#control_bar').fadeOut(400, function() {
  ﻿    $('#control_bar').remove();
      cropImage(startX - scrollLeft, startY - scrollTop, endX - scrollLeft, endY - scrollTop);
    });
    cleanUp();
  }
  if (message.data == 'cancel') {
    canvasContainer.remove();
    $('#control_bar').fadeOut(400, function() {
  ﻿    $('#control_bar').remove();
    });
    cleanUp();
  }
}

function handleMouseUp(e) {
  isDrawing = false;
  canvas.style.cursor = "default";
  endX = e.clientX - offsetX + scrollLeft;
  endY = e.clientY - offsetY + scrollTop;
}

function handleMouseMove(e) {
  if (isDrawing) {
    hasDrawn = true;
    var mouseX = parseInt(e.clientX - offsetX + scrollLeft);
    var mouseY = parseInt(e.clientY - offsetY + scrollTop);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.rect(startX, startY, mouseX - startX, mouseY - startY);
    ctx.stroke();

    drawShading(mouseX, mouseY);
  }
}

function drawShading(mouseX, mouseY){
  var lowX;
  var lowY;
  var highX;
  var highY;

  if(startX < mouseX){
    lowX = startX;
    highX = mouseX;
  }else{
    lowX = mouseX;
    highX = startX;
  }

  if(startY < mouseY){
    lowY = startY;
    highY = mouseY;
  }else{
    lowY = mouseY
    highY = startY;
  }

  ctx.globalAlpha = 0.6;

  ctx.beginPath();
  ctx.rect(0, 0, lowX, canvas.height);
  ctx.fill();

  ctx.beginPath();
  ctx.rect(highX, 0, (canvas.width - highX), canvas.height);
  ctx.fill();

  ctx.beginPath();
  ctx.rect(lowX, 0, (highX-lowX), lowY);
  ctx.fill();

  ctx.beginPath();
  ctx.rect(lowX, highY, (highX-lowX), canvas.height - highY);
  ctx.fill();
}

function handleMouseDown(e) {           
  isDrawing = true;
  doc = document.documentElement;
  scrollLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
  scrollTop = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
  startX = parseInt(e.clientX - offsetX + scrollLeft);
  startY = parseInt(e.clientY - offsetY + scrollTop);
}

function cropImage(x1, y1, x2, y2) {
  var sourceWidth = Math.abs(x2-x1);
  var sourceHeight = Math.abs(y2-y1);

  var lowX;
  var lowY;

  if(x1 < x2){
  ﻿  lowX = x1;
  }else{
  ﻿  lowX = x2;
  }

  if(y1 < y2){
  ﻿  lowY = y1;
  }else{
  ﻿  lowY = y2
  }
  
  chrome.runtime.sendMessage(
    {greeting: "cropImage",
     x: lowX,
     y: lowY,
     width: sourceWidth,
     height: sourceHeight}
  );
}
function cleanUp(){
  started = false;
  hasDrawn = false;
  document.documentElement.style.overflow = 'auto';
  document.documentElement.style.height = 'auto';
}